package plugins;

import interfaces.Algorithm;
import interfaces.Board;
import interfaces.Cell;
import interfaces.Command;
import interfaces.State;

public class ConwayAlgorithm implements Algorithm {

	private static ConwayAlgorithm thisAlgorithm = new ConwayAlgorithm();
	
	private ConwayAlgorithm() {}
	
	/**
	 * Returns the algorithm for Conway's game of life.
	 *
	 * @return the algorithm
	 */
	public static Algorithm getAlgorithm() {
		return thisAlgorithm;
	}

	/* (non-Javadoc)
	 * @see interfaces.Algorithm#act(interfaces.Board, interfaces.Cell)
	 */
	@Override
	public Command act(Board b, Cell c, int row, int col) {
		if(!(c instanceof ConwayCell)) return null;
		int liveCount = 0;
		State st = new AliveState();
		for(int i = row-1; i < row+2; i++)
			for(int j = col-1; j < col+2; j++)
				if(b.getCell(i,j) != null)
					if(b.getCell(i, j).getState().getClass() == st.getClass())
						if(b.getCell(i, j) != c)
							liveCount++;
		if(c.getState() instanceof AliveState){
			if(liveCount < 2 || liveCount > 3) return new DieCommand(c);
		}
		else if(c.getState() instanceof DeadState){
			if(liveCount == 3) return new LiveCommand(c);
		}
		return null;
	}	
}
